import {
    Injectable,
    NestInterceptor,
    ExecutionContext,
    CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface Response<T> {
    data: T;
    code: number;
    globalError?: boolean;
}
export class GlobalError extends Error {
    constructor(message) {
        super(message);
        this.name = 'GlobalError';
    }
}

/**
 * 这个函数直接返回一个http error
 */
export function globalError(res: any) {
    throw new GlobalError(res);
}

export function NotAllowError() {
    globalError('无权操作');
}

@Injectable()
export class HttpResultTransformInterceptor<T>
    implements NestInterceptor<T, Response<T>> {
    intercept(
        context: ExecutionContext,
        next: CallHandler<T>,
    ): Observable<Response<T>> {
        let result = next.handle().pipe(
            map((data: any) => {
                if (data && data.code > 0 && data.globalError) {
                    return data as Response<T>;
                }
                // console.log(data);
                return {
                    data: typeof data == 'undefined' ? 'success' : data,
                    code: 0,
                } as Response<T>;
            }),
        );
        return result;
    }
}
